/**
 * @title: FlowRuleMysqlDataSource
 * @projectName mscloud
 * @Description TODO
 * @Author
 * @Date 2022/2/23 16:03
 */
package com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.datasource;

import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.bean.dto.SentinelFlowRuleDTO;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.convert.impl.FlowRuleMysqlConverter;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.service.FlowRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class FlowRuleMysqlDataSource extends AutoRefreshDataSource<List<SentinelFlowRuleDTO>,List<FlowRule>> {
    @Value("${spring.application.name}")
    String applicationName;
    @Autowired
    FlowRuleService flowRuleService;
    public FlowRuleMysqlDataSource(FlowRuleMysqlConverter flowRuleMysqlConverter){
        super(flowRuleMysqlConverter,flowRuleMysqlConverter.getRecommendRefreshMs());
    }

    @PostConstruct
    public void init() {
        try {
            List<FlowRule> flowRules = loadConfig();
            getProperty().updateValue(flowRules);

        } catch (Exception e) {
            RecordLog.info("RuleMysqlDataSource loadConfig exception", e);
        }

    }

    @Override
    public List<SentinelFlowRuleDTO> readSource() throws Exception {
        return flowRuleService.findByApplicationName(applicationName).collectList().block();
    }
}
